package org.zyj.io.example.case6;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.zyj.io.example.codec.protobuf.StudentDto;

import java.nio.charset.StandardCharsets;

/**
 * 描述
 *
 * @author zhouyijin
 * @date 2022-01-14 16:29:33
 */
public class ProtobufClientHandler extends ChannelInboundHandlerAdapter {

    //当通道就绪的时候, 会被调用
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel actived, ctx = " + ctx);
        var zyj = StudentDto.Student.newBuilder().setId(1).setName("zyj").build();
        ctx.writeAndFlush(zyj);
    }

    //当通道有读取时间时, 会触发
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        System.out.println("服务器回复: " + buf.toString(StandardCharsets.UTF_8));
        System.out.println("服务器地址: " + ctx.channel().remoteAddress());
    }


    //异常处理
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
